package hos.demo;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.UriUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import hos.base.Launcher;
import hos.cache.StorageFile;
import hos.cache.StorageSp;
import hos.demo.databinding.ActivityMainBinding;
import hos.java.compat.FileTypeCompat;
import hos.java.util.IDUtils;
import hos.java.util.MapUtils;
import hos.location.LocationSource;
import hos.location.LocationSourceAndroidData;
import hos.location.LocationSourceAndroidDataCache;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding activityMainBinding;

    private LocationSource locationSource = null;
    private LocationSource.Location location;
    private String pathCamera;
    private ActivityResultLauncher<Uri> cameraLauncher;
    private ActivityResultLauncher<String> imageLauncher;

    private String pathVideo;

    private ActivityResultLauncher<String> imageMultipleLauncher;
    private ActivityResultLauncher<String> videoLauncher1;
    private ActivityResultLauncher<String[]> videoLauncher2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        locationSource = new LocationSourceAndroidDataCache(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//            FpsMonitor.toggle();
        }
        activityMainBinding.btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isSuccess = StorageFile.saveCache("file", "张三");
                Toast.makeText(MainActivity.this, "是否成功：" + isSuccess, Toast.LENGTH_SHORT).show();
            }
        });
        activityMainBinding.btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String value = StorageFile.getData("file");
                Toast.makeText(MainActivity.this, "结果：" + value, Toast.LENGTH_SHORT).show();
            }
        });
        activityMainBinding.btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long start = System.currentTimeMillis();
                User user = new User(System.currentTimeMillis(), "张三", "12345678", false);
                if (location == null) {
                    location = locationSource.getLocation();
                }
                boolean isSuccess = StorageFile.saveCache("location", location);
                if (location instanceof LocationSourceAndroidData.LocationData) {
                    StorageFile.saveCache("androidLocation", (Parcelable) ((LocationSourceAndroidData.LocationData) location).getLocation());
                }
                long end = System.currentTimeMillis();
                Log.i("TAG", "time: " + (end - start));
                Toast.makeText(MainActivity.this, "是否成功：" + isSuccess, Toast.LENGTH_SHORT).show();
            }
        });
        activityMainBinding.btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long start = System.currentTimeMillis();
                LocationSource.Location value = StorageFile.getData("location", LocationSource.Location.CREATOR);
                long end = System.currentTimeMillis();
                Log.i("TAG", "time: " + (end - start));
                if (value != null) {
                    android.location.Location androidLocation = StorageFile.getData("androidLocation", android.location.Location.CREATOR);
                    if (androidLocation == null) {
                        value = new LocationSourceAndroidData.LocationData(value);
                    } else {
                        value = new LocationSourceAndroidData.LocationData(value, androidLocation);
                    }
                    Toast.makeText(MainActivity.this, "结果：" + value.toString(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "结果：失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        activityMainBinding.btn5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long start = System.currentTimeMillis();
                User user = new User(System.currentTimeMillis(), "李四", "12345678", false);
                boolean isSuccess = StorageSp.saveCache("userSP", user);
                long end = System.currentTimeMillis();
                Log.i("TAG", "time: " + (end - start));
                Toast.makeText(MainActivity.this, "是否成功：" + isSuccess, Toast.LENGTH_SHORT).show();
            }
        });
        activityMainBinding.btn6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long start = System.currentTimeMillis();
                User value = StorageSp.getData("userSP");
                long end = System.currentTimeMillis();
                Log.i("TAG", "time: " + (end - start));
                if (value != null) {
                    Toast.makeText(MainActivity.this, "结果：" + value.toString(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "结果：失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        activityMainBinding.btn7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long start = System.currentTimeMillis();
                boolean clearSp = StorageSp.clear();
                boolean clearFile = StorageFile.clear();
                long end = System.currentTimeMillis();
                Log.i("TAG", "time: " + (end - start));
                Toast.makeText(MainActivity.this, "结果：sp:" + clearSp + " file:" + clearFile, Toast.LENGTH_SHORT).show();
            }
        });
        activityMainBinding.btn8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("int", 1);
                map.put("double", 1.1);
                map.put("string", "string");
                MapUtils.orEmpty(map, "int");
                Log.i("TAG", "int: " + MapUtils.orEmpty(map, "int"));
                Log.i("TAG", "double: " + MapUtils.orEmpty(map, "double"));
                Log.i("TAG", "string: " + MapUtils.orEmpty(map, "string"));
            }
        });
        cameraLauncher = Launcher.createPictureCamera(this, new ActivityResultCallback<Boolean>() {
            @Override
            public void onActivityResult(Boolean result) {
                if (!result) {
                    if (BuildConfig.DEBUG) {
                        Log.d("path", "cameraLauncher CAMERA: " + false);
                    }
                    return;
                }
                if (BuildConfig.DEBUG) {
                    Log.d("path", "cameraLauncher CAMERA: " + pathCamera);
                    Log.d("path", "cameraLauncher CAMERA: " + FileUtils.isFileExists(pathCamera));
                }
            }
        });
        activityMainBinding.btn9.setOnClickListener(
                view -> {
                    pathCamera = PathUtils.getFilesPathExternalFirst() + File.separator + IDUtils.genNanoId() + ".jpg";
                    FileUtils.createFileByDeleteOldFile(pathCamera);
                    Uri uri = UriUtils.file2Uri(FileUtils.getFileByPath(pathCamera));
                    cameraLauncher.launch(uri);
//                    Intent intent = LaunchUtils.getCamera(pathCamera);
//                    startActivityForResult(intent, LaunchCompat.REQUEST_CODE_CAMERA);
                }
        );
        ActivityResultLauncher<Uri> videoLauncher = Launcher.createVideoCamera(this, new ActivityResultCallback<Bitmap>() {
            @Override
            public void onActivityResult(Bitmap result) {
//                if (result == null) {
//                    if (BuildConfig.DEBUG) {
//                        Log.d("path", "videoLauncher Video: " + false);
//                    }
//                    return;
//                }
                // 保存封皮
//                ImageUtils.save(result, pathVideoImage, Bitmap.CompressFormat.JPEG);
                if (BuildConfig.DEBUG) {
                    Log.d("path", "videoLauncher Video: " + pathVideo);
                    Log.d("path", "videoLauncher Video: " + FileUtils.isFileExists(pathVideo));
                    Log.d("path", "videoLauncher Video: " + FileUtils.getFileByPath(pathVideo).length());
//                    Log.d("path", "videoLauncher Video: " + pathVideoImage);
//                    Log.d("path", "videoLauncher Video: " + FileUtils.isFileExists(pathVideoImage));
//                    Log.d("path", "videoLauncher Video: " + FileUtils.getFileByPath(pathVideoImage).length());
                }
            }
        });
        activityMainBinding.btn10.setOnClickListener(
                view -> {
                    pathVideo = PathUtils.getFilesPathExternalFirst() + File.separator + IDUtils.genNanoId() + ".mp4";
                    FileUtils.createOrExistsFile(pathVideo);
                    videoLauncher.launch(UriUtils.file2Uri(FileUtils.getFileByPath(pathVideo)));
//                    Intent intent = LaunchUtils.getVideo();
//                    startActivityForResult(intent, LaunchCompat.REQUEST_CODE_VIDEO);
                }
        );

        ActivityResultLauncher<Uri> audioLauncher = Launcher.createAudioCamera(this, new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                if (result == null) {
                    if (BuildConfig.DEBUG) {
                        Log.d("path", "audioLauncher Video: " + false);
                    }
                    return;
                }
                // 保存封皮
                if (BuildConfig.DEBUG) {
                    File file = UriUtils.uri2File(result);
                    Log.d("path", "audioLauncher Audio: " + file.getAbsolutePath());
                    Log.d("path", "audioLauncher Audio: " + FileUtils.isFileExists(file));
                    Log.d("path", "audioLauncher Audio: " + file.length());
                }
            }
        });
        activityMainBinding.btn11.setOnClickListener(
                view -> {
                    audioLauncher.launch(null);

//                    Intent intent = LaunchUtils.getAudio();
//                    startActivityForResult(intent, LaunchCompat.REQUEST_CODE_SOUND);
                }
        );
        imageLauncher = Launcher.openContent(this, new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                if (result == null) {
                    if (BuildConfig.DEBUG) {
                        Log.d("path", "imageLauncher ALBUM: " + false);
                    }
                    return;
                }
                if (BuildConfig.DEBUG) {
                    Log.d("path", "imageLauncher ALBUM: " + UriUtils.uri2File(result).getAbsolutePath());
                }
            }
        });
        activityMainBinding.btn12.setOnClickListener(
                view -> {
                    imageLauncher.launch(FileTypeCompat.Type.IMAGE.getType());
//                    Intent intent = LaunchUtils.getFile(FileTypeCompat.Type.IMAGE);
//                    startActivityForResult(intent, LaunchCompat.REQUEST_CODE_ALBUM);
                }
        );
        imageMultipleLauncher = Launcher.openMultipleContents(this, new ActivityResultCallback<List<Uri>>() {
            @Override
            public void onActivityResult(List<Uri> result) {
                if (result == null) {
                    if (BuildConfig.DEBUG) {
                        Log.d("path", "imageMultipleLauncher ALBUM: " + false);
                    }
                    return;
                }
                if (BuildConfig.DEBUG) {
                    for (Uri uri : result) {
                        Log.d("path", "imageMultipleLauncher ALBUM: " + UriUtils.uri2File(uri).getAbsolutePath());
                    }

                }
            }
        });
        activityMainBinding.btn13.setOnClickListener(
                view -> {
                    imageMultipleLauncher.launch(FileTypeCompat.Type.IMAGE.getType());
//                    Intent intent = LaunchUtils.getFile(FileTypeCompat.Type.IMAGE);
//                    startActivityForResult(intent, LaunchCompat.REQUEST_CODE_ALBUM);
                }
        );
        videoLauncher1 = Launcher.openContent(this, new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                if (result == null) {
                    if (BuildConfig.DEBUG) {
                        Log.d("path", "videoLauncher1 ALBUM: " + false);
                    }
                    return;
                }
                if (BuildConfig.DEBUG) {
                    Log.d("path", "videoLauncher1 ALBUM: " + UriUtils.uri2File(result).getAbsolutePath());

                }
            }
        });
        activityMainBinding.btn14.setOnClickListener(
                view -> {
                    videoLauncher1.launch(FileTypeCompat.Type.VIDEO.getType());
                }
        );
        videoLauncher2 = Launcher.openMultipleDocument(this, new ActivityResultCallback<List<Uri>>() {
            @Override
            public void onActivityResult(List<Uri> result) {
                if (result == null) {
                    if (BuildConfig.DEBUG) {
                        Log.d("path", "videoLauncher2 ALBUM: " + false);
                    }
                    return;
                }
                if (BuildConfig.DEBUG) {
                    for (Uri uri : result) {
                        Log.d("path", "videoLauncher2 ALBUM: " + UriUtils.uri2File(uri).getAbsolutePath());
                    }

                }
            }
        });
        activityMainBinding.btn15.setOnClickListener(
                view -> {
                    videoLauncher2.launch(new String[]{FileTypeCompat.Type.VIDEO.getType()});
                }
        );
        locationSource.addLocationChangedListener(new LocationSource.LocationChangedListener() {
            @Override
            public void locationChanged(LocationSource.LocationChangedEvent locationChangedEvent) {
                location = locationChangedEvent.getLocation();
            }
        });
        locationSource.startLocation();

        ActivityResultLauncher<String[]> multiplePermissions = Launcher.requestMultiplePermissions(this, new ActivityResultCallback<Map<String, Boolean>>() {
            @Override
            public void onActivityResult(Map<String, Boolean> result) {

            }
        });
        multiplePermissions.launch(new String[]{
                Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO, Manifest.permission.CAPTURE_AUDIO_OUTPUT, Manifest.permission.MODIFY_AUDIO_SETTINGS,
                "android.permission.CAPTURE_VIDEO_OUTPUT", "android.permission.CAPTURE_SECURE_VIDEO_OUTPUT",
        });
//        PermissionUtils.permissionGroup(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
//                .request();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode != Activity.RESULT_OK) {
//            return;
//        }
//        if (requestCode == LaunchCompat.REQUEST_CODE_ALBUM) {
//            if (BuildConfig.DEBUG && data != null) {
//                Uri uri = data.getData();
//                if (uri != null) {
//                    Log.d("path", "ALBUM: " + UriUtils.uri2File(uri).getAbsolutePath());
//                }
//            }
//        }
//        if (requestCode == LaunchCompat.REQUEST_CODE_CAMERA) {
//            if (BuildConfig.DEBUG) {
//                Log.d("path", "CAMERA: " + pathCamera);
//                Log.d("path", "CAMERA: " + FileUtils.isFileExists(pathCamera));
//            }
//        }
//        if (requestCode == LaunchCompat.REQUEST_CODE_VIDEO) {
//            if (BuildConfig.DEBUG && data != null) {
//                Uri uri = data.getData();
//                if (uri != null) {
//                    Log.d("path", "VIDEO: " + UriUtils.uri2File(uri).getAbsolutePath());
//                    return;
//                }
//            }
//        }
//        if (requestCode == LaunchCompat.REQUEST_CODE_SOUND) {
//            if (BuildConfig.DEBUG && data != null) {
//                Uri uri = data.getData();
//                if (uri != null) {
//                    Log.d("path", "SOUND: " + UriUtils.uri2File(uri).getAbsolutePath());
//                    return;
//                }
//            }
//        }
//        if (BuildConfig.DEBUG && data != null) {
//            Uri uri = data.getData();
//            if (uri != null) {
//                Log.d("path", "onActivityResult: " + UriUtils.uri2File(uri).getAbsolutePath());
//            }
//        }
    }

    @Override
    protected void onDestroy() {
        locationSource.stopLocation();
        super.onDestroy();
    }
}